package com.menggudf.interceptor;

import com.alibaba.fastjson.JSON;
import com.menggudf.constant.Constants;
import com.menggudf.http.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author zengqingdong 2023/8/15
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");
        String body = new RequestWrapper(request).getBody();
        log.info("路径：{},收到的参数：{}",request.getServletPath(),body);

        if(true){
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }

        if(Objects.isNull(authorization)){
            log.error("authorization为空");
            log.warn("token过期，请重新登陆");
            response.setStatus(Constants.NOT_TOKEN_AUTH);
            return false;
        }
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        String token = authorization.replace("Bearer", "").trim();
        String key = Constants.TOKEN_USER_INFO_CACHE_PREFIX + token;
        Object tokenObj = valueOperations.get(key);
        if(Objects.isNull(tokenObj)){
            log.error("tokenObj为空");
            log.warn("token过期，请重新登陆");
            response.setStatus(Constants.NOT_TOKEN_AUTH);
            return false;
        }
        Object json = JSON.toJSON(tokenObj);
        log.info("当前登陆用户信息:{}",json.toString());
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }



}
